﻿//*** Guidance generated code ***//
using System;
using System.Collections.Generic;
using System.Diagnostics.Contracts;
using System.Globalization;
using System.Linq;
using System.Web.Mvc;
using System.Web.Security;

using Survey.Filters;

using ProjectBase.Core;
using ProjectBase.Core.Web;
using ProjectBase.Mvc;
using ProjectBase.Mvc.Controllers;

using Survey.Common;
using Survey.Entity.Services;
using Survey.Common.Controllers;
using Survey.Common.Models;
using Survey.Common.Business.Services;

namespace Survey.Mvc.Controllers
{
    public class MembershipController : WebController<IMembershipModel>, IMembershipController
    {
        #region index
        public override ActionResult Index()
        {
            OnBeforeAction(SecurityManager.Identity.IsAuthenticated
                ? Str.Business.Services.Change
                : Str.Business.Services.Logon);

            return View("Membership", Model);
        }
        #endregion index

        #region AOP Roles
        /// <summary>
        ///     Renders screen where you can change current role
        /// </summary>
        /// <returns></returns>
        [ChangeRole(DoSelectRole = true)]
        public virtual ActionResult SelectRole()
        {
            OnBeforeAction(Str.Business.Services.SelectRole);

            return View("Membership", Model);
        }

        /// <summary>
        ///     This is a marking action which at the base implementation
        ///     returns nothing.
        ///     The AOP filter RoleAccess can be called via attribute
        ///     to handle the ComboBox control rendering
        /// </summary>
        /// <returns>rendered combo box with roles available for current user</returns>
        [ChangeRole(DoGetComboBoxWCRoles = true)]
        public virtual ActionResult ComboBoxRoles()
        {
            return null;
        }

        /// <summary>
        ///     This action is used for RoleAccess filter attribute.
        ///     If called, AOP will change user current role
        /// </summary>
        /// <returns></returns>
        [ChangeRole(DoChangeCurrentRole = true)]
        [Transaction]
        public virtual ActionResult RoleSelected()
        {
            return RedirectToAction(Str.Actions.Default, Str.Controllers.Home);
        }
        #endregion AOP Roles

        #region Logon Logoff
        public virtual ActionResult Logon()
        {
            OnBeforeAny();
            OnBeforeAction(Str.Business.Services.Logon);

            return View("Membership", Model);
        }

        [HttpPost]
        public ActionResult LogonMember(string returnUrl)
        {
            OnBeforeAny();

            if (BindModel(Model.Member))
            {
                if (UserFacade.ValidateUser(Model.Member.UserName, Model.Member.Password))
                {
                    return SignIn(Model.Member.UserName, Model.Member.RememberMe)
                        ? RedirectToAction(Str.Actions.Default, Str.Controllers.Home)
                        : RedirectToAction("Logon");
                }

                OnBeforeAction(Str.Business.Services.Logon);

                this.PublishWarning(Str.Messages.LogonFailed);
            }

            // If we got this far, something failed, redisplay form
            return View("Membership", Model);
        }

        public ActionResult LogOff()
        {
            SignOut();

            return RedirectToAction(Str.Actions.Default, Str.Controllers.Home);
        }
        #endregion Logon Logoff

        #region Register
        public ActionResult Register()
        {
            OnBeforeAny();
            OnBeforeAction(Str.Business.Services.Register);

            return View("Membership", Model);
        }

        [HttpPost]
        [Transaction]
        public ActionResult RegisterMember()
        {
            OnBeforeAny();

            if (BindModel(Model.Member))
            {
                if (UserFacade.CreateMember(Model.Member).Equals(MembershipCreateStatus.Success))
                {
                    return SignIn(Model.Member.UserName, false)
                        ? RedirectToAction(Str.Actions.Default, Str.Controllers.Home)
                        : RedirectToAction("Index");
                }

                OnBeforeAction(Str.Business.Services.Register);

                this.PublishWarning(Str.Messages.RegistrationFailed);
            }
            return View("Membership", Model);
        }
        #endregion Register

        #region Change
        public ActionResult Change()
        {
            OnBeforeAny();
            OnBeforeAction(Str.Business.Services.Change);

            return View("Membership", Model);
        }

        [HttpPost]
        [Transaction]
        public ActionResult ChangeMember()
        {
            OnBeforeAny();

            if (BindModel(Model.Member))
            {
                if (UserFacade.UpdateMember(Model.Member))
                {
                    return View("Membership", Model);
                }

                OnBeforeAction(Str.Business.Services.Change);

                this.PublishWarning(Str.Messages.MemberUpdateFailed);
            }
            return View("Membership", Model);
        }
        #endregion Change

        #region ValidationRules
        public virtual ActionResult ValidationRules(string id, string filter = null)
        {
            return JavaScript(UserFacade.ValidationRulesToString(filter));
        }
        #endregion ValidationRules

        #region protected
        protected virtual void OnBeforeAny()
        {
            Model.Member = new Member();

            if (SecurityManager.Identity.IsAuthenticated)
            {
                Model.Member.UserName = SecurityManager.UserLogin;
                Model.Member.FirstName = SecurityManager.User.FirstName;
                Model.Member.Surname = SecurityManager.User.LastName;
            }

        }
        protected virtual void OnBeforeAction(string actionName)
        {
            if (actionName.IsEmpty())
            {
                return;
            }

            if (!SecurityManager.IsAuthenticationModeForms)
            {
                return;
            }

            if (actionName.Equals(Str.Business.Services.Register))
            {
                this.AddAction(Str.Business.Services.Logon, Url)
                    .AddAction(Str.Business.Services.Register, Url);
            }
            else if (actionName.Equals(Str.Business.Services.Logon))
            {
                this.AddAction(Str.Business.Services.Logon, Url)
                    .AddAction(Str.Business.Services.Register, Url);
            }
            else if (actionName.Equals(Str.Business.Services.Change))
            {
                this.AddAction(Str.Business.Services.Logoff, Url)
                    .AddAction(Str.Business.Services.SelectRole, Url)
                    .AddAction(Str.Business.Services.Change, Url);
            }
            else if (actionName.Equals(Str.Business.Services.SelectRole))
            {
                this.AddAction(Str.Business.Services.Logoff, Url)
                    .AddAction(Str.Business.Services.SelectRole, Url)
                    .AddAction(Str.Business.Services.Change, Url);
            }



            Model.MasterModel.ButtonSubmit = new ButtonItem(actionName)
            {
                FormAction = actionName + "Member",
                FormController = ControllerName,
            };
            Model.ValidationRulesJS = Url.Action(Constants.Actions.Special.ValidationRules
                , new { filter = actionName, id = CultureInfo.CurrentCulture.Name });
        }
        protected virtual bool SignIn(string userName, bool createPersistentCookie)
        {
            if (userName.IsEmpty())
            {
                this.PublishError("Value cannot be null or empty: 'userName'");
                return false;
            }
            FormsAuthentication.SetAuthCookie(userName, createPersistentCookie);
            return true;
        }
        protected virtual void SignOut()
        {
            FormsAuthentication.SignOut();
        }
        #endregion protected

        #region properties
        public override string ControllerName { get { return Str.Controllers.Membership; } }
        public virtual IUserFacade UserFacade { get; set; }
        #endregion properties
    }
}